import { Injectable } from '@nestjs/common';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import * as XLSX from 'xlsx';
import { extname, join } from 'path';
import * as ip from 'ip';
const docx = require('docx');
const fs = require('fs');
const mammoth = require('mammoth');
const fuzzaldrin = require('fuzzaldrin-plus');
const stringSimilarity = require('string-similarity');
// 将word文档拆分成数组
async function splitParagraphsFromWord(filePath: string): Promise<string[]> {
  try {
    const data = await fs.promises.readFile(filePath);
    const result = await mammoth.extractRawText({ buffer: data });
    const paragraphs = result.value.split('\n\n');
    return paragraphs;
  } catch (err) {
    console.error(err);
  }
}
// 对比两个字符串输出他们之间的相似度
function compareStrings(str1, str2) {
  // const score = fuzzaldrin.score('12', '12');
  // console.log(score);
  const similarity = stringSimilarity.compareTwoStrings(str1, str2);
  return similarity;
}
@Injectable()
export class UploadService {
  IP: string;
  constructor() {
    this.IP = ip.address();
  }
  changeExcel(file: any) {
    const removeColmn = [
      '单据状态',
      '库存组织',
      '客户代码',
      '客户',
      '收货地址',
      '收货人',
      '原运输方式',
      '原承运商',
      '特殊要求',
      '出库备注',
      '物流信息',
      '创建人',
      '创建时间',
      '修改人',
      '修改时间',
      '备注',
    ];
    const startRow = 5;
    // 读取excel文件
    const workbook = XLSX.readFile(join(__dirname, '../../../', file.path));
    const sheetNames = workbook.SheetNames;
    const sheet1 = workbook.Sheets[sheetNames[0]];
    const range = XLSX.utils.decode_range(sheet1['!ref']);
    const titleArr: string[] = [];
    const jsonData: any[] = [];
    //循环获取单元格值，假设第一行是标题，将
    for (let R = startRow; R <= range.e.r; ++R) {
      const row_value = {};
      for (let C = range.s.c; C <= range.e.c; ++C) {
        const cell_address = { c: C, r: R }; //获取单元格地址
        const cell = XLSX.utils.encode_cell(cell_address); //根据单元格地址获取单元格
        //获取单元格值
        if (R === startRow) {
          // 过滤掉removeColmn包含的列
          if (removeColmn.includes(sheet1[cell]?.v)) continue;
          titleArr[C] = sheet1[cell]?.v;
        } else {
          if (!titleArr[C]) continue;
          if (titleArr[C] === '费用合计') {
            row_value[titleArr[C]] = Number(sheet1[cell]?.v || 0);
          } else {
            row_value[titleArr[C]] = sheet1[cell]?.v;
          }
        }
        // console.log(range);
      }
      if (R > startRow) {
        jsonData.push(row_value);
      }
      // console.log(row_value);
    }
    // console.log(ip.address());

    // 将数据转成workSheet
    const jsonWorkSheet = XLSX.utils.json_to_sheet(jsonData);
    // console.log(jsonData);
    // console.log(titleArr);
    // 构造workBook
    const workBook = {
      SheetNames: ['jsonWorkSheet'],
      Sheets: {
        jsonWorkSheet: jsonWorkSheet,
      },
    };
    // 将workBook写入文件
    XLSX.writeFile(workBook, join(__dirname, '../../../', file.path));
    file.url = `http://${process.env.localURL}:3000/${file.path}`;
    file.data = jsonData;
    file.headers = titleArr.filter((item) => item !== null);
    return file;
  }
  uploadAvatar(file: any) {
    file.url = `http://${process.env.localURL}:3000/${file.path}`;
    return file;
  }

  async excuteWord(file: any) {
    // 读取word并根据文章段落进行拆分，拆成数组
    const url = join(__dirname, '../../../', file.path);
    file.url = url;
    return {
      file,
    };
  }

  async wordDiff(url1: string, url2: string): Promise<any[]> {
    const paragraphs1 = await splitParagraphsFromWord(url1);
    const paragraphs2 = await splitParagraphsFromWord(url2);

    // 创建一个 Set 用于存储 paragraphs2 的值，便于快速查找
    const setParagraphs2 = new Set(paragraphs2);

    // 用于存储结果
    const matches = new Map<string, { str2: string; score: number }>();

    paragraphs1.forEach((str1) => {
      if (setParagraphs2.has(str1)) {
        matches.set(str1, { str2: str1, score: 1 });
      } else {
        for (const str2 of paragraphs2) {
          if (!str1 || !str2) continue;
          const score = compareStrings(str1, str2);
          if (score > 0.8) {
            matches.set(str1, { str2, score });
            break; // 找到匹配后立即退出循环
          }
        }
      }
    });

    // 将 Map 转换为数组返回
    return Array.from(matches.entries()).map(([str1, { str2, score }]) => ({
      str1,
      str2,
      score,
    }));
  }

  create(createUploadDto: CreateUploadDto) {
    return 'This action adds a new upload';
  }

  findAll() {
    return `This action returns all upload`;
  }

  findOne(id: number) {
    return `This action returns a #${id} upload`;
  }

  update(id: number, updateUploadDto: UpdateUploadDto) {
    return `This action updates a #${id} upload`;
  }

  remove(id: number) {
    return `This action removes a #${id} upload`;
  }
}
